<template>
  <div class="class-detail-page">
    <!-- 顶部基础信息栏 -->
    <div class="top-info">
      <span class="info-item">培训班编号：{{ trainingClassCode || '-' }}</span>
      <span class="info-splitter">|</span>
      <span class="info-item">培训班名称：{{ className || '-' }}</span>
      <span class="info-splitter">|</span>
      <span class="info-item status-tag" :class="statusTagClass">
        交接状态：{{ transferStatusText }}
      </span>
    </div>




    <!-- 标签页内容区 -->
    <el-tabs v-model="activeTab" type="card" class="custom-tabs" tab-position="top">
      <!-- 1. 班级数据标签页 -->
      <el-tab-pane label="班级数据" name="classData">
        <div class="tab-content">
          <!-- 班级基本信息 -->
          <div class="section-container">
            <h3 class="section-title">班级基本信息</h3>
            <el-table
              :data="classBasicInfo"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; max-width: 800px; margin-bottom: 24px;"
            >
              <el-table-column prop="label" label="项目" width="140" align="center" />
              <el-table-column prop="value" label="内容" align="left" />
              <el-table-column prop="label2" label="项目" width="140" align="center" />
              <el-table-column prop="value2" label="内容" align="left">
                <template #default="scope">
                  <span v-if="scope.row.action" class="action-link">{{ scope.row.action }}</span>
                  <span v-else>{{ scope.row.value2 }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 组成人员 -->
          <div class="section-container">
            <h3 class="section-title">组成人员</h3>
            <el-table
              :data="members"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; max-width: 300px; margin-bottom: 24px;"
            >
              <el-table-column prop="type" label="人员类型" align="center" />
              <el-table-column prop="name" label="姓名" align="center" />
            </el-table>
          </div>

          <!-- 培训课程 -->
          <div class="section-container">
            <h3 class="section-title">培训课程</h3>
            <el-table
              :data="courses"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; max-width: 500px; margin-bottom: 24px;"
            >
              <el-table-column prop="name" label="课程名称" align="left" />
              <el-table-column prop="type" label="课程类型" align="center" width="100" />
              <el-table-column prop="hours" label="学时" align="center" width="80" />
            </el-table>
          </div>

          <!-- 培训教师 -->
          <div class="section-container">
            <h3 class="section-title">培训教师</h3>
            <el-table
              :data="teachers"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; max-width: 500px; margin-bottom: 24px;"
            >
              <el-table-column prop="course" label="课程名称" align="left" />
              <el-table-column prop="department" label="部门" align="left" />
            </el-table>
          </div>

          <!-- 培训教材 -->
          <div class="section-container">
            <h3 class="section-title">培训教材</h3>
            <el-table
              :data="materials"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; margin-bottom: 24px;"
            >
              <el-table-column prop="name" label="教材名称" align="left" />
              <el-table-column prop="publisher" label="出版社" align="center" width="150" />
              <el-table-column prop="isbn" label="ISBN" align="center" width="160" />
              <el-table-column prop="publishTime" label="出版时间" align="center" width="120" />
              <el-table-column prop="price" label="单价" align="center" width="80" />
            </el-table>
          </div>

          <!-- 培训耗材 -->
          <div class="section-container">
            <h3 class="section-title">培训耗材</h3>
            <el-table
              :data="supplies"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; margin-bottom: 24px;"
            >
              <el-table-column prop="name" label="耗材名称" align="left" />
              <el-table-column prop="classCount" label="数量（按班级）" align="center" width="120" />
              <el-table-column prop="studentCount" label="数量（按学员）" align="center" width="120" />
              <el-table-column prop="studentNum" label="学员人数" align="center" width="100" />
              <el-table-column prop="total" label="合计" align="center" width="80" />
              <el-table-column prop="desc" label="说明" align="left" />
            </el-table>
          </div>

          <!-- 培训考试 -->
          <div class="section-container">
            <h3 class="section-title">培训考试</h3>
            <el-table
              :data="exams"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; margin-bottom: 24px;"
            >
              <el-table-column prop="group" label="考试题组" align="left" />
              <el-table-column prop="type" label="题组类型" align="center" width="120" />
              <el-table-column prop="totalQuestions" label="题组题量" align="center" width="120" />
              <el-table-column prop="selectedQuestions" label="设置题量" align="center" width="120" />
              <el-table-column prop="scorePerQ" label="每题分数" align="center" width="100" />
              <el-table-column prop="totalScore" label="分数合计" align="center" width="100" />
            </el-table>
          </div>

          <!-- 培训证书 -->
          <div class="section-container">
            <h3 class="section-title">培训证书</h3>
            <el-table
              :data="certificates"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; max-width: 400px; margin-bottom: 24px;"
            >
              <el-table-column prop="name" label="证书" align="left" />
              <el-table-column prop="type" label="证书类型" align="center" width="120" />
            </el-table>
          </div>

          <!-- 培训计划 -->
          <div class="section-container">
            <h3 class="section-title">培训计划</h3>
            <el-table
              :data="trainingPlans"
              border
              stripe
              size="mini"
              :cell-style="{ 'vertical-align': 'middle' }"
              style="width: 100%; margin-bottom: 24px;"
            >
              <el-table-column prop="content" label="培训内容" align="left" />
              <el-table-column prop="startTime" label="开始时间" align="center" width="180" />
              <el-table-column prop="endTime" label="结束时间" align="center" width="180" />
              <el-table-column prop="location" label="培训地点" align="center" width="150" />
              <el-table-column prop="teacher" label="培训教师" align="center" width="120" />
              <el-table-column prop="desc" label="说明" align="left" />
            </el-table>
          </div>
        </div>
      </el-tab-pane>

      <!-- 2. 学员数据标签页 -->
      <el-tab-pane label="学员数据" name="studentData">
        <div class="tab-content">
          <el-table
            :data="studentData"
            @selection-change="handleSelectionChange"
            border
            stripe
            size="mini"
            :cell-style="{ 'vertical-align': 'middle' }"
            style="width: 100%; margin-bottom: 16px;"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" align="center" width="100" />
            <el-table-column prop="idCard" label="证件编号" align="center" width="180" />
            <el-table-column prop="sex" label="性别" align="center" width="80" />
            <el-table-column prop="phonenumber" label="电话" align="center" width="130" />
            <el-table-column prop="qualification" label="学历" align="center" width="140" >
              <template slot-scope="scope">
                    <dict-tag
                      :options="dict.type.pxzx_xl"
                      :value="scope.row.qualification"
                    />
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="单位" show-overflow-tooltip></el-table-column>
            <el-table-column prop="position" label="职务职级" show-overflow-tooltip></el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            size="mini"
            style="text-align: right; margin-top: 8px;"
          />
        </div>
      </el-tab-pane>

      <!-- 3. 培训计划标签页 -->
      <el-tab-pane label="培训计划" name="trainingPlan">
        <training-plan-table
          :class-id="classId"
          @submitSuccess="handlePlanSubmitSuccess"
        ></training-plan-table>
      </el-tab-pane>

      <!-- 4. 实践情况标签页 -->
      <el-tab-pane label="实践情况" name="practice">
        <practice-table
          :class-id="classId"
          @edit="handleEdit"
          @view-reservations="handleViewReservations"
          @selection-change="handleSelectionChange"
        ></practice-table>
      </el-tab-pane>

      <!-- 5. 签到情况标签页 -->
      <el-tab-pane label="签到情况" name="signIn">
        <!-- 引入标签切换组件 -->
        <sign-tabs
          :class-id="classId"
          @tab-change="handleTabChange"
        />
        <!-- <sign-tabs
          :class-id="classId"
          @tab-change="handleTabChange"
          @update:selected-rows="rows => selectedRows = rows"
          @update:filtered-list="list => filteredList = list"
          :search-form="searchForm"
          @show-sign-detail="showSignDetail"
        /> -->
      </el-tab-pane>

      <!-- 6. 通知情况标签页 -->
      <el-tab-pane label="通知情况" name="notification">
        <div class="tab-content">
          <el-table
            :data="notificationData"
            border
            stripe
            size="mini"
            :cell-style="{ 'vertical-align': 'middle' }"
            style="width: 100%; margin-bottom: 16px;"
          >
            <el-table-column prop="index" label="序号" align="center" width="80" />
            <el-table-column prop="time" label="通知时间" align="center" width="180" />
            <el-table-column prop="channel" label="通知渠道" align="center" width="180" />
            <el-table-column prop="content" label="通知内容" align="left" />
            <el-table-column prop="publisher" label="发布人" align="center" />
            <el-table-column prop="people" label="通知人员" align="left" />
            <!-- <el-table-column prop="operation" label="操作" align="center" width="120">
              <template #default="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="viewNoticeDetail(scope.row)"
                  class="operation-btn"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column> -->
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="notificationData.length"
            size="mini"
            style="text-align: right; margin-top: 8px;"
          />
        </div>
      </el-tab-pane>

      <!-- 7. 考试安排标签页 -->
      <el-tab-pane label="考试安排" name="examArrangement">
        <div class="tab-content">
          <el-table
            :data="examArrangementData"
            border
            stripe
            size="mini"
            :cell-style="{ 'vertical-align': 'middle' }"
            style="width: 100%; max-width: 600px; margin-bottom: 24px;"
          >
            <el-table-column prop="label" label="项目" align="center" width="160" />
            <el-table-column prop="value" label="内容" align="left" />
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 8. 费用结算标签页 -->
      <el-tab-pane label="费用结算" name="expenseSettlement">
        <class-settlement-table :classId="classId"></class-settlement-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑班级弹窗 -->
    <el-dialog
      :title="editOpen ? '编辑班级' : '新增班级'"
      :visible.sync="editOpen"
      width="800px"
      append-to-body
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
        class="edit-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训班编号" prop="trainingClassCode">
              <el-input
                v-model="editForm.trainingClassCode"
                placeholder="请输入培训班编号"
                :disabled="!editForm.isNewRecord"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训班名称" prop="trainingClassName">
              <el-input
                v-model="editForm.trainingClassName"
                placeholder="请输入培训班名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 替换后的培训部门和项目选择器 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训部门" prop="trainingDepartmentId">
              <el-select
                v-model="editForm.trainingDepartmentId"
                placeholder="请选择培训部门"
                clearable
              >
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.id"
                  :label="dept.label"
                  :value="dept.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训项目" prop="trainingProjectId">
              <el-select
                v-model="editForm.trainingProjectId"
                placeholder="请选择培训项目"
                clearable
              >
                <el-option
                  v-for="project in projectOptions"
                  :key="project.id"
                  :label="project.label"
                  :value="project.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训开始日期" prop="startDate">
              <el-date-picker
                v-model="editForm.startDate"
                type="date"
                placeholder="选择开始日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训截止日期" prop="endDate">
              <el-date-picker
                v-model="editForm.endDate"
                type="date"
                placeholder="选择截止日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名截止日期" prop="registrationDate">
              <el-date-picker
                v-model="editForm.registrationDate"
                type="date"
                placeholder="选择报名截止日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总名额" prop="totalQuota">
              <el-input
                v-model.number="editForm.totalQuota"
                placeholder="请输入总名额"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 替换后的班主任选择器 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班主任1" prop="headTeacherId1">
              <el-select
                v-model="editForm.headTeacherId1"
                placeholder="请选择班主任1"
                clearable
              >
                <el-option
                  v-for="teacher in teacherOptions"
                  :key="teacher.id"
                  :label="teacher.name"
                  :value="teacher.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班主任2" prop="headTeacherId2">
              <el-select
                v-model="editForm.headTeacherId2"
                placeholder="请选择班主任2"
                clearable
              >
                <el-option
                  v-for="teacher in teacherOptions"
                  :key="teacher.id"
                  :label="teacher.name"
                  :value="teacher.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训地址" prop="trainingAddress">
              <el-input
                v-model="editForm.trainingAddress"
                placeholder="请输入培训地址"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训场地" prop="trainingVenue">
              <el-input
                v-model="editForm.trainingVenue"
                placeholder="请输入培训场地"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否需要考试" prop="needExam">
              <el-radio-group v-model="editForm.needExam">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级状态" prop="classStatus">
              <el-select
                v-model="editForm.classStatus"
                placeholder="请选择班级状态"
                disabled
              >
                <el-option label="未开始" value="0"></el-option>
                <el-option label="进行中" value="1"></el-option>
                <el-option label="已结束" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="editForm.remarks"
                placeholder="请输入备注信息"
                type="textarea"
                rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </div>
    </el-dialog>

    <!-- 1. 班级备注弹窗 -->
    <el-dialog
      title="班级备注"
      :visible.sync="classDialogVisible"
      width="800px"
      @close="resetClassRemarkForm"
    >
      <el-form
        ref="classRemarkFormRef"
        :model="classRemarkForm"
        class="remark-form"
        :rules="classRemarkRules"
      >
        <el-form-item label="备注内容" label-width="80px" prop="content">
          <el-input
            type="textarea"
            v-model="classRemarkForm.content"
            placeholder="请输入班级备注内容"
            rows="4"
            class="remark-textarea"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="备注历史" label-width="80px">
          <el-table
            :data="classRemarkHistory"
            border
            stripe
            size="mini"
            :cell-style="{ 'vertical-align': 'middle' }"
            style="width: 100%;"
            :loading="classRemarkLoading"
            empty-text="暂无班级备注记录"
          >
            <el-table-column prop="createTime" label="时间" width="200"></el-table-column>
            <el-table-column prop="createBy" label="备注人" width="150"></el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="300"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="mini" @click="classDialogVisible = false">取消</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="submitClassRemark"
            :loading="classRemarkSubmitting"
          >提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 2. 学员备注弹窗 -->
    <el-dialog
      :title="studentRemarkTitle"
      :visible.sync="studentDialogVisible"
      width="800px"
      @close="resetStudentRemarkForm"
      class="dialog-remark"
    >
      <el-form
        ref="studentRemarkFormRef"
        :model="studentRemarkForm"
        label-width="80px"
        :rules="studentRemarkRules"
      >
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="studentRemarkForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入学员备注内容"
            style="width: 100%"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="备注历史">
          <el-table
            :data="studentRemarkHistory"
            border
            style="width: 100%"
            :show-header="true"
            :loading="studentRemarkLoading"
            empty-text="暂无学员备注记录"
          >
            <el-table-column prop="createTime" label="时间" width="200"></el-table-column>
            <el-table-column prop="createBy" label="备注人" width="150"></el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="300"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="studentDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitStudentRemark"
          :loading="studentRemarkSubmitting"
        >提交</el-button>
      </div>
    </el-dialog>

    <!-- 二维码弹出框 -->
    <el-dialog
      title="培训班二维码"
      :visible.sync="CodeVisible"
      width="800px"
      @close="resetCode"
      class="dialog-remark"
      center
    >
      <div class="qrcode-container">
        <img
          :src="qrcodeUrl"
          alt="培训班二维码"
          class="qrcode-img"
          @error="handleQrcodeError"
        >
        <div v-if="qrcodeError" class="qrcode-error">
          二维码图片加载失败，请稍后重试
        </div>
        <div class="qrcode-desc">
          扫码查看
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="CodeVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 学员详情弹窗 -->
    <el-dialog
      title="学员详情"
      :visible.sync="detailVisible"
      width="800px"
      append-to-body
    >
      <el-form :model="form" label-width="120px" class="detail-form">
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号">
              <el-input :value="form.id || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input :value="form.name || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证件编号">
              <el-input :value="form.idCard || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-input :value="form.gender || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input :value="form.phone || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称">
              <el-input :value="form.company || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">报名信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名来源">
              <el-input :value="mapRegistrationMethod(form.registerSource) || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训类型">
              <el-input :value="mapTrainingType(form.trainingType) || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="缴费状态">
              <el-input
                :value="mapPaymentStatus(form.feeStatus) || '无'"
                disabled
                readonly
                class="non-interactive-input"
                :style="{ color: form.feeStatus === '未交费' ? 'red' : 'green' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名时间">
              <el-input :value="form.registerTime || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">档案信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="档案状态">
              <el-input :value="form.fileStatus || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="档案缺失情况">
              <el-input :value="form.fileMissing || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提交状态">
              <el-input :value="form.submitStatus || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">其他信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否办结">
              <el-input :value="form.isCompleted || '无'" disabled readonly class="non-interactive-input"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                :value="form.remark || '无'"
                disabled
                readonly
                class="non-interactive-input"
                type="textarea"
                rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 学员通知弹窗 -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="noticeDialogVisible"
      width="50%"
      :before-close="handleNoticeDialogClose"
    >
      <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
        <el-form-item label="通知类型" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0">短信</el-checkbox>
            <el-checkbox label="1">门户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            placeholder="请输入通知内容"
            rows="6"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="发送范围">
          <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
            <el-radio label="all">所有学员</el-radio>
            <el-radio label="selected">指定学员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="noticeForm.range === 'selected'"
          class="selected-users-form-item"
          prop="selectedUsers"
          :rules="[{ required: true, message: '请至少选择一个学员', trigger: 'change' }]"
        >
          <el-select
            v-model="noticeForm.selectedUsers"
            multiple
            placeholder="请输入学员姓名搜索并选择"
            filterable
            remote
            :remote-method="queryUsers"
            :loading="userLoading"
            style="width: 100%;"
            clearable
            @clear="handleSelectClear"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.studentId"
              :label="user.studentName"
              :value="user.studentId"
            >
              <span style="float: left">{{ user.studentName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                身份证号：{{ user.idCard || '无证件号' }}
              </span>
            </el-option>
            <template #empty>
              <div style="text-align: center; color: #909399;">
                {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
              </div>
            </template>
          </el-select>
          <div class="selected-count" v-if="noticeForm.range === 'selected'">
            已选择 {{ noticeForm.selectedUsers.length }} 名学员
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
      </div>
    </el-dialog>

    <!-- 班级交接弹窗 -->
    <el-dialog
      title="班级交接"
      :visible.sync="handoverDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="handoverFormRef" :model="handoverForm" label-width="120px">
        <el-form-item label="接收人" prop="receiveUserId" :rules="[{ required: true, message: '请选择接收人', trigger: 'change' }]">
          <el-select v-model="handoverForm.receiveUserId" placeholder="请选择接收人" clearable>
            <el-option
              v-for="user in teacherOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交接备注" prop="remark">
          <el-input
            v-model="handoverForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入交接备注（可选）"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handoverDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandover">确认交接</el-button>
      </div>
    </el-dialog>

    <classSettlementDialog
      :visible.sync="showSettlement"
      :classId="settlementClassId"
      @confirm="handleSettlementConfirm"
    ></classSettlementDialog>
  </div>
</template>

<script>
import { trainingClassList, getTrainingClass, classHandover, saveTrainingClass, deleteTrainingClass, exportClassDetail, exportFeeSettlement } from "@/api/training/TrainingClass";
import { getClassStudents, batchQuit } from "@/api/training/ClassStudent";
import { listRemarksByParams, addRemarks } from "@/api/training/remarks";
import { studentNoticeProcess } from "@/api/training/studentNotice.js";
import classSettlementDialog from '@/components/class/classSettlementDialog.vue'
import trainingPlanTable from '@/components/class/trainingPlanTable.vue'
import practiceTable from '@/components/class/practiceTable.vue'
import signTabs from '@/components/class/signTabs.vue';
import classSettlementTable from '@/components/class/classSettlementTable.vue';
import { queryNonMemberUsers, deptTreeSelect } from "@/api/system/user"
import { projectTreeSelect, } from "@/api/training/projects";
import { listNoticeByClassId, } from "@/api/training/studentNotice";
import { getByClassId, } from "@/api/training/examSchedule";


export default {
  name: "ClassDetail",
  components: { classSettlementDialog,trainingPlanTable,practiceTable,signTabs,classSettlementTable },
  dicts: ["training_type", "class_status", "payment_status","pxzx_xl",
   "bmlb", "registration_method", "start_up_type", "record_status", "submit_status"],
  data() {
    return {
      // 编辑班级相关
      editOpen: false,
      editForm: {
        trainingClassId: '',
        trainingClassCode: '',
        trainingClassName: '',
        trainingDepartmentId: '',
        trainingProjectId: '',
        startDate: '',
        endDate: '',
        registrationDate: '',
        totalQuota: 0,
        headTeacherId1: '',
        headTeacherId2: '',
        trainingAddress: '',
        trainingVenue: '',
        needExam: '0',
        classStatus: '0',
        remarks: '',
        isNewRecord: true
      },
      editRules: {
        trainingClassCode: [
          { required: true, message: '请输入培训班编号', trigger: 'blur' },
          { max: 50, message: '编号长度不能超过50个字符', trigger: 'blur' }
        ],
        trainingClassName: [
          { required: true, message: '请输入培训班名称', trigger: 'blur' },
          { max: 100, message: '名称长度不能超过100个字符', trigger: 'blur' }
        ],
        trainingDepartmentId: [
          { required: true, message: '请选择培训部门', trigger: 'change' }
        ],
        trainingProjectId: [
          { required: true, message: '请选择培训项目', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '请选择培训开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择培训截止日期', trigger: 'change' }
        ],
        registrationDate: [
          { required: true, message: '请选择报名截止日期', trigger: 'change' }
        ],
        totalQuota: [
          { required: true, message: '请输入总名额', trigger: 'blur' },
          { type: 'number', min: 0, message: '名额不能为负数', trigger: 'blur' }
        ]
      },
      departmentOptions: [],
      projectOptions: [],
      teacherOptions: [],

      // 费用结算
      settlementClassId: "",
      showSettlement: false,
      // 培训班基本信息
      classId: '',
      className: '',
      handoverStatus: '',
      trainingClassCode: '',
      selectionDto: [],
      ids: [],
      single: true,
      multiple: true,

      // 二维码相关
      CodeVisible: false,
      qrcodeUrl: 'http://127.0.0.1:9300/statics/2025/09/19/1_20250919113028A006.jpg',
      qrcodeError: false,

      activeTab: "classData",
      searchForm: {
        name: "",
        phone: "",
        idCard: "",
        reportStatus: ""
      },
      showSearch: true,
      pageInfo: {
        currentPage: 1,
        pageSize: 10,
        total: 100
      },

      // 班级结算相关
      settlementDialogVisible: false,
      incomeItems: [
        { id: 1, feeItem: '', quantity: '', unitPrice: '', subtotal: '0.00', remark: '', isNew: true },
        { id: 2, feeItem: '', quantity: '', unitPrice: '', subtotal: '0.00', remark: '', isNew: true },
      ],
      expenseItems: [
        { id: 1, feeItem: '', quantity: '', unitPrice: '', subtotal: '0.00', remark: '', isNew: true },
        { id: 2, feeItem: '', quantity: '', unitPrice: '', subtotal: '0.00', remark: '', isNew: true },
      ],
      nextIncomeId: 3,
      nextExpenseId: 3,

      // 班级备注相关
      classDialogVisible: false,
      classRemarkForm: { content: "" },
      classRemarkHistory: [],
      classRemarkLoading: false,
      classRemarkSubmitting: false,
      classRemarkRules: {
        content: [{ required: true, message: "请输入班级备注内容", trigger: "blur" }]
      },

      // 学员备注相关
      studentDialogVisible: false,
      studentRemarkForm: { remarks: "", studentId: null },
      studentRemarkHistory: [],
      studentRemarkTitle: "",
      studentRemarkLoading: false,
      studentRemarkSubmitting: false,
      studentRemarkRules: {
        remarks: [{ required: true, message: "请输入学员备注内容", trigger: "blur" }]
      },

      // 学员详情弹窗
      detailVisible: false,
      form: {
        id: '', name: '', phone: '', idCard: '', gender: '', company: '',
        registerSource: '', trainingType: '', feeStatus: '', fileStatus: '',
        fileMissing: '', submitStatus: '', isCompleted: '', registerTime: '', remark: ''
      },

      // 学员通知弹窗
      noticeDialogVisible: false,
      noticeLoading: false,
      noticeForm: {
        title: '', content: '', range: 'all', selectedUsers: [], sendTypes: []
      },
      noticeRules: {
        sendTypes: [{ required: true, message: '请选择通知类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }, { max: 500, message: '内容不能超过500个字符', trigger: 'blur' }]
      },
      userOptions: [],
      allUsers: [],
      userLoading: false,

      // 字典相关
      dictLoaded: false,
      dictCheckTimer: null,

      // 班级交接弹窗
      handoverDialogVisible: false,
      handoverForm: {
        receiveUserId: '',
        remark: ''
      },

      // 标签页数据
      classBasicInfo: [],
      members: [],
      courses: [],
      teachers: [],
      materials: [],
      supplies: [],
      exams: [],
      certificates: [],
      trainingPlans: [],
      trainingPlanData: [],
      practiceContent: [],
      practiceStudentData: [],
      signInData: [],
      notificationData: [],
      examArrangementData: [],
      expenseData: [],
      studentData: [],
      TrainingClassList: [],
      trainingClassInfo: null,
      userFlagId: null,
      memberOptions: [],
      classUseData:null,
    };
  },
  created() {
    this.initDictCheck();
    this.getList();
    this.waitForDictLoad().then(() => {
      this.getMembersList();
      this.loadDepartments();
      this.loadProjects();
      this.loadTeachers();
      this.userFlagId = this.$store.state.user.id;
    });
  },
  beforeDestroy() {
    if (this.dictCheckTimer) clearInterval(this.dictCheckTimer);
  },
  watch: {
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId
        this.getTrainingClassInfo()
        // this.trainingClassCode = params.trainingClassCode
        // this.className = params.className
        // this.handoverStatus = params.handoverStatus
        // this.activeTab = params.activeTab || "classData"
        this.activeTab = params.activeTab || "classData"
      }
    }
  },
  computed: {
    registrationMethodMap() {
      return this.dict.label.registration_method || {};
    },
    trainingTypeMap() {
      return this.dict.label.training_type || {};
    },
    paymentStatusMap() {
      return this.dict.label.payment_status || {};
    },
    startupTypeMap() {
      return this.dict.label.start_up_type || {};
    },
    recordStatusMap() {
      return this.dict.label.record_status || { "0": "不完整", "1": "完整" };
    },
    submitStatusMap() {
      return this.dict.label.submit_status || { "0": "未提交", "1": "已提交" };
    },
    isDictReady() {
      return this.dictLoaded &&
        Object.keys(this.registrationMethodMap).length > 0 &&
        Object.keys(this.trainingTypeMap).length > 0 &&
        Object.keys(this.paymentStatusMap).length > 0 &&
        Object.keys(this.startupTypeMap).length > 0;
    },
    transferStatusText() {
      const statusMap = {
        "0": "未交接",
        "1": "交接中",
        "2": "已交接"
      };
      return statusMap[this.handoverStatus] || "未交接";
    },
    statusTagClass() {
      const statusMap = {
        "0": "status-pending",
        "1": "status-processing",
        "2": "status-completed"
      };
      return statusMap[this.handoverStatus] || "status-pending";
    }
  },
  methods: {
    statusStr(id){
      if(id === "0"){
        return "未交接"
      }else if(id === "1"){
        return "交接中"
      }else if(id === "2"){
        return  "已交接"
      }else{
        return "交接状态有误"
      }
    },
    async getTrainingClassInfo(){
      try {
        const res = await getTrainingClass(this.classId);
        this.className = res.data.trainingClassName;
        this.handoverStatus = this.statusStr(res.data.handoverStatus);
        this.trainingClassCode =res.data.trainingClassCode;
      } catch (err) {
        this.$message.error('获取班级信息失败：' + (err.msg || err.message));
      }
    },
    // 加载部门列表
    async loadDepartments() {
      try {
        const res = await deptTreeSelect();
        this.departmentOptions = this.flattenTree(res.data || []);
      } catch (error) {
        console.error("部门数据加载失败：", error);
        this.departmentOptions = [];
      }
    },

    // 加载项目列表
    async loadProjects() {
      try {
        const res = await projectTreeSelect();
        this.projectOptions = this.flattenTree(res.data || []);
      } catch (error) {
        console.error("项目数据加载失败：", error);
        this.projectOptions = [];
      }
    },

    // 加载教师列表
    async loadTeachers() {
      try {
        const res = await queryNonMemberUsers();
        this.teacherOptions = (res.rows || []).map(teacher => ({
          id: teacher.userId?.toString() || '', // 用 userId 作为选项值（转为字符串，避免类型问题）
          name: teacher.nickName || teacher.userName || '未知用户', // 显示名称优先用 nickName，其次 userName
          label: teacher.nickName || teacher.userName || '未知用户',
        }));
      } catch (error) {
        console.error("教师数据加载失败：", error);
        this.teacherOptions = [];
      }
    },

    // 将树形结构扁平化为列表（带层级缩进）
    flattenTree(tree, result = [], level = 0) {
      if (!tree || !tree.length) return result;

      for (const node of tree) {
        result.push({
          id: node.id,
          label: '　'.repeat(level) + node.label,
          original: node
        });

        if (node.children && node.children.length) {
          this.flattenTree(node.children, result, level + 1);
        }
      }

      return result;
    },

    // 取消编辑
    cancelEdit() {
      this.editOpen = false;
      this.resetEditForm();
    },

    handlePlanSubmitSuccess(data) {
      // 处理培训计划提交成功后的逻辑
      console.log('培训计划提交成功', data);
    },

    // 重置编辑表单
    resetEditForm() {
      this.editForm = {
        trainingClassId: '',
        trainingClassCode: '',
        trainingClassName: '',
        trainingDepartmentId: '',
        trainingProjectId: '',
        startDate: '',
        endDate: '',
        registrationDate: '',
        totalQuota: 0,
        headTeacherId1: '',
        headTeacherId2: '',
        trainingAddress: '',
        trainingVenue: '',
        needExam: '0',
        classStatus: '0',
        remarks: '',
        isNewRecord: true
      };
      if (this.$refs.editFormRef) {
        this.$refs.editFormRef.resetFields();
      }
    },

    // 提交编辑表单
    async submitEditForm() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              ...this.editForm,
              // 映射回后端需要的字段名
              trainingDepartment: this.editForm.trainingDepartmentId,
              trainingProject: this.editForm.trainingProjectId,
              headTeacher1: this.editForm.headTeacherId1,
              headTeacher2: this.editForm.headTeacherId2
            };

            // 删除临时字段
            delete params.trainingDepartmentId;
            delete params.trainingProjectId;
            delete params.headTeacherId1;
            delete params.headTeacherId2;

            params.totalQuota = Number(params.totalQuota);
            params.needExam = Number(params.needExam);
            params.classStatus = Number(params.classStatus);

            const res = await saveTrainingClass(params);
            this.$message.success(this.editForm.isNewRecord ? '班级创建成功' : '班级更新成功');
            this.editOpen = false;
            this.getList();
            this.resetEditForm();
          } catch (error) {
            this.$message.error('操作失败：' + (error.msg || error.message || '未知错误'));
          }
        }
      });
    },

    // 加载人员列表数据
    async getMembersList() {
      try {
        const userRes = await queryNonMemberUsers();
        this.memberOptions = userRes.rows || [];
      } catch (error) {
        console.error("人员数据加载失败：", error);
        this.$message.error("人员信息加载失败，请稍后重试");
        this.memberOptions = [];
      }
    },

    // 查看通知详情
    viewNoticeDetail(row) {
      this.$message.info(`
        通知详情：
        通知时间：${row.time}
        通知渠道：${row.channel}
        通知内容：${row.content}
        通知人员：${row.people}
        发布人：${row.publisher}
      `);
    },

    // 交接确定
    async handleHandover() {
      try {
        const res = await classHandover({
          completeHandover: "true",
          trainingClassId: this.trainingClassInfo?.trainingClassId || this.classId
        });
        this.$message.success(`班级 "${this.className}" 交接完成`);
        this.handoverDialogVisible = false;
        this.getList();
      } catch (err) {
        this.$message.error('交接确定失败：' + (err.msg || err.message || '操作失败'));
      }
    },

    // 编辑班级信息
    handleUpdateSingle() {
      if (this.classId !== null && this.classId !== "") {
        this.getEditClassData(this.classId);
      }
    },

    // 获取编辑班级数据并打开弹窗
async getEditClassData(classId) {
  // 确保所有选项数据都已加载
  try {
    // 并行加载所有必要的选项数据
    await Promise.all([
      this.loadDepartments(),
      this.loadProjects(),
      this.loadTeachers()
    ]);

    const response = await getTrainingClass(classId);
    this.classUseData=response.data ;
    let resData = { ...response.data };

    // 确保状态值为字符串类型，与表单选项匹配
    resData.classStatus = resData.classStatus?.toString() || '';
    resData.trainingType = resData.trainingType?.toString() || '';
    resData.needExam = resData.needExam?.toString() || '';

    // 处理部门ID可能为数字的情况，转为字符串以匹配选项值类型
    const deptId = resData.trainingDepartment?.toString() || '';
    const projectId = resData.trainingProject?.toString() || '';
    const headTeacher1 = resData.headTeacher1?.toString() || '';
    const headTeacher2 = resData.headTeacher2?.toString() || '';

    // 验证部门ID是否存在于选项中
    const deptExists = this.departmentOptions.some(option => option.id === deptId);
    const projectExists = this.projectOptions.some(option => option.id === projectId);
    const teacher1Exists = this.teacherOptions.some(option => option.id?.toString() === headTeacher1);
    const teacher2Exists = this.teacherOptions.some(option => option.id?.toString() === headTeacher2);

    // 如果不存在，可能是数据同步问题，记录警告
    if (!deptExists && deptId) {
      console.warn(`部门ID ${deptId} 不在选项列表中`);
    }
    if (!projectExists && projectId) {
      console.warn(`项目ID ${projectId} 不在选项列表中`);
    }

    // 映射表单数据
    this.editForm = {
      ...resData,
      trainingDepartmentId: deptExists ? deptId : '',
      trainingProjectId: projectExists ? projectId : '',
      headTeacherId1: teacher1Exists ? headTeacher1 : '',
      headTeacherId2: teacher2Exists ? headTeacher2 : '',
      isNewRecord: false
    };

    this.editOpen = true;

    // 强制刷新表单，解决某些情况下的回显延迟问题
    this.$nextTick(() => {
      if (this.$refs.editFormRef) {
        this.$refs.editFormRef.resetFields();
      }
    });
  } catch (error) {
    this.$message.error("加载班级数据失败：" + (error.msg || "未知错误"));
  }
},


// 修改flattenTree方法，确保ID为字符串类型
flattenTree(tree, result = [], level = 0) {
  if (!tree || !tree.length) return result;

  for (const node of tree) {
    result.push({
      id: node.id?.toString() || '', // 确保ID为字符串
      label: '　'.repeat(level) + node.label,
      original: node
    });

    if (node.children && node.children.length) {
      this.flattenTree(node.children, result, level + 1);
    }
  }

  return result;
},

    // 查找节点
    findNodeById(nodes, id) {
      if (!nodes || !nodes.length) return null;
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children && node.children.length) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    // 学员进出班
    handleStudentEnter() {
      this.$router.push({
        name: '学员进出班管理',
        params: {
          className:this.classUseData.trainingClassName,
          classId: this.classUseData.trainingClassId,
          handoverStatus: this.statusStr(this.classUseData.handoverStatus),
          projectId:this.classUseData.trainingProject,
          trainingClassCode:this.classUseData.trainingClassCode
        }
      });
    },

    statusStr(id){
      if(id === "0"){
        return "未交接"
      }else if(id === "1"){
        return "交接中"
      }else if(id === "2"){
        return  "已交接"
      }else{
        return "交接状态有误"
      }
    },
    // 班级学员
    handleClassStudents() {
      // 准备要传递的数据
      const paramsData = {
        className: this.classUseData.trainingClassName,
        classId: this.classId,
        handoverStatus: this.statusStr(this.classUseData.handoverStatus),
        trainingClassCode: this.classUseData.trainingClassCode,
        projectId:this.classUseData.trainingProject,
      }

      this.$router.push({
        name: '班级学员',
        params: paramsData
      });
    },

    // 设置班级信息
    handleSetMembers() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 1,
          classId: this.classId,
        }
      });
    },

    // 添加收入项
    addIncomeItem() {
      this.incomeItems.push({
        id: this.nextIncomeId++,
        feeItem: '',
        quantity: '',
        unitPrice: '',
        subtotal: '0.00',
        remark: '',
        isNew: true
      });
    },

    // 删除收入项
    deleteIncomeItem(id) {
      this.incomeItems = this.incomeItems.filter(item => item.id !== id);
    },

    // 添加支出项
    addExpenseItem() {
      this.expenseItems.push({
        id: this.nextExpenseId++,
        feeItem: '',
        quantity: '',
        unitPrice: '',
        subtotal: '0.00',
        remark: '',
        isNew: true
      });
    },

    // 删除支出项
    deleteExpenseItem(id) {
      this.expenseItems = this.expenseItems.filter(item => item.id !== id);
    },

    // 计算小计
    calculateSubtotal(item, type) {
      const quantity = Number(item.quantity) || 0;
      const unitPrice = Number(item.unitPrice) || 0;
      item.subtotal = (quantity * unitPrice).toFixed(2);

      if (type === 'income') {
        this.incomeItems = [...this.incomeItems];
      } else {
        this.expenseItems = [...this.expenseItems];
      }
    },

    // 结算确认
    handleSettlementConfirm() {
      this.$message.success('班级结算已保存');
      this.settlementDialogVisible = false;
    },

    // 费用结算
    handleFeeSettlement() {
      this.showSettlement = true
      this.settlementClassId = this.classId
    },

    // 选择学员变化
    handleSelectionChange(selection) {
      this.selectionDto = selection;
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 班级二维码
    handleCode() {
      this.CodeVisible = true;
    },

    // 重置二维码
    resetCode() {
      this.qrcodeError = false;
    },

    // 二维码加载失败
    handleQrcodeError() {
      this.qrcodeError = true;
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-');
    },

    // 获取列表数据
    async getList() {
      try {
        const response = await getTrainingClass(this.classId);
        this.classUseData=response.data ;
        const notificationDataRes = await listNoticeByClassId(this.classId);
        // 适配前端表格字段
        this.notificationData = notificationDataRes.rows.map((item, index) => {
          return {
            index: index + 1, // 序号从1开始
            time: item.sendTime || item.createTime || '-', // 优先用发送时间，无则用创建时间，默认显示'-'
            channel: item.noticeChannel || '-', // 通知渠道，默认显示'-'
            content: item.noticeContent || '-', // 通知内容，默认显示'-'
            people: item.noticeStudents || '-', // 通知人员，默认显示'-'
            publisher: item.sendBy || '-' // 发布人，默认显示'-'
          };
        });
        // 获取考试安排数据
        const examArrangementDataRes = await getByClassId(this.classId);

        // 定义需要展示的考试项目（字段映射+格式化）
        const examFields = [
          { field: 'paperConfigName', label: '试卷名称' },
          { field: 'examStartTime', label: '考试开始时间' },
          { field: 'examEndTime', label: '考试结束时间' },
          { field: 'examDuration', label: '考试时长' },
          { field: 'examLocation', label: '考试地点' },
          { field: 'examPathwayName', label: '考试途径' },
          {
            field: 'examPassScore',
            label: '通过分数',
            formatter: (val) => val ? `${val}分` : '-' // 补充单位
          },
          {
            field: 'ifReleaseResultsImmediately',
            label: '是否立即公布成绩',
            formatter: (val) => val === '1' ? '是' : val === '0' ? '否' : '-'
          },
          {
            field: 'ifAgreeAutomaticExam',
            label: '是否允许自动考试',
            formatter: (val) => val === '1' ? '是' : val === '0' ? '否' : '-'
          },
          { field: 'resultsAnnouncementTime', label: '成绩公布时间' },
          { field: 'examTimes', label: '考试次数', formatter: (val) => val || '-' },
          { field: 'teacherName', label: '监考老师' }
        ];

        // 转换数据为前端表格所需格式
        this.examArrangementData = [];
        examArrangementDataRes.data.forEach((exam, index) => {
          // 添加考试标题（区分多个考试）
          this.examArrangementData.push({
            label: `考试安排${index + 1}`,
            value: exam.paperConfigName || '未知考试'
          });

          // 添加当前考试的具体项目
          examFields.forEach(item => {
            let value = exam[item.field];
            // 应用格式化函数（如有）
            if (item.formatter) {
              value = item.formatter(value);
            } else {
              // 处理空值
              value = value || '-';
            }
            this.examArrangementData.push({
              label: item.label,
              value: value
            });
          });

          // 多个考试之间添加空行分隔（可选，提升可读性）
          if (index !== examArrangementDataRes.data.length - 1) {
            this.examArrangementData.push({ label: '', value: '' });
          }
        });


        const res = await trainingClassList({ trainingClassCode: this.trainingClassCode });
        const classData = res.rows && res.rows.length > 0 ? res.rows[0] : {};

        this.classId = classData.trainingClassId || '';
        this.className = classData.trainingClassName || '';
        this.trainingClassCode = classData.trainingClassCode || '';
        this.handoverStatus = classData.handoverStatus || '';
        this.trainingClassInfo = classData;
        this.classBasicInfo = [
          {
            label: "报名类别",
            value: this.mapSignUpCategory(classData.signUpCategory) || "-",
            label2: "报名项目",
            value2: classData.trainingProjectNames || "-"
          },
          {
            label: "培训班编号",
            value: classData.trainingClassCode || "-",
            label2: "培训班名称",
            value2: classData.trainingClassName || "-"
          },
          {
            label: "年份",
            value: classData.trainingYear || new Date().getFullYear(),
            label2: "期次",
            value2: classData.trainingSession || "-"
          },
          {
            label: "开班类型",
            value: this.mapStartupType(classData.startupType) || "-",
            label2: "培训类别",
            value2: this.mapTrainingType(classData.trainingType) || "-"
          },
          {
            label: "培训部门",
            value: classData.trainingDepartmentName || "-",
            label2: "班级状态",
            value2: this.mapClassStatus(classData.classStatus) || "-"
          },
          {
            label: "培训开始日期",
            value: classData.startDate || "-",
            label2: "培训截止日期",
            value2: classData.endDate || "-"
          },
          {
            label: "报名截止日期",
            value: classData.registrationDate || "-",
            label2: "培训地区",
            value2: this.mapTrainingRegion(classData.trainingRegion) || "-"
          },
          {
            label: "培训地址",
            value: classData.trainingAddress || "-",
            label2: "培训场地",
            value2: classData.trainingVenue || "-"
          },
          {
            label: "实际培训场地",
            value: classData.actualTrainingVenue || "-",
            label2: "总名额",
            value2: classData.totalQuota || "0"
          },
          {
            label: "已报名人数",
            value: classData.registeredCount || "0",
            label2: "班主任1",
            value2: classData.headTeacher1Name || "-"
          },
          {
            label: "班主任2",
            value: classData.headTeacher2Name || "-",
            label2: "考试安排",
            value2: classData.needExam === 1 ? "需要考试" : "无需考试"
          },
          {
            label: "考试时间",
            value: classData.examTime || "-",
            label2: "考试地点",
            value2: classData.examLocation || "-"
          },
          {
            label: "附件",
            value: classData.attachmentName || "-",
            label2: "组成状态",
            value2: classData.compositionStatus || "-"
          },
          {
            label: "课程状态",
            value: classData.courseStatus || "-",
            label2: "教师状态",
            value2: classData.teacherStatus || "-"
          },
          {
            label: "教材状态",
            value: classData.textbookStatus || "-",
            label2: "耗材状态",
            value2: classData.consumablesStatus || "-"
          },
          {
            label: "考试状态",
            value: classData.examStatus || "-",
            label2: "证书状态",
            value2: classData.certificateStatus || "-"
          },
        ];

        const studentRes = await getClassStudents({
          trainingClassId: this.classId,
          pageNum: this.pageInfo.currentPage,
          pageSize: this.pageInfo.pageSize
        });

        this.studentData = studentRes.rows.map(item => {
          const dto = item.student || {};
          return {
            id: dto.registrationId || "-",
            name: dto.studentName || "-",
            idCard: dto.idNumber || "-",
            sex: dto.sex,
            phonenumber: dto.phonenumber || "-",
            unitName: dto.unitName || "-",
            qualification:dto.qualification,
            position:dto.position
          };
        });
        this.pageInfo.total = studentRes.total || 0;


      } catch (err) {
        this.$message.error('获取数据失败：' + (err.msg || err.message));
      }
    },

    // 映射报名类别
    mapSignUpCategory(type) {
      const map = {
        'regular': '常规报名',
        'emergency': '紧急报名',
      };
      return map[type] || type;
    },

    // 映射班级状态
    mapClassStatus(status) {
      const map = {
        '0': '未开始',
        '1': '进行中',
        '2': '已结束',
      };
      return map[status] || status;
    },

    // 映射培训地区
    mapTrainingRegion(region) {
      const map = {
        '1': '华东地区',
        '2': '华南地区',
        '3': '华北地区',
      };
      return map[region] || region;
    },

    // 初始化字典检查
    initDictCheck() {
      this.dictCheckTimer = setInterval(() => {
        if (this.checkDictReady()) {
          this.dictLoaded = true;
          clearInterval(this.dictCheckTimer);
        }
      }, 100);
    },

    // 检查字典是否准备好
    checkDictReady() {
      return this.dict &&
        this.dict.label &&
        Object.keys(this.dict.label).length > 0;
    },

    // 等待字典加载完成
    waitForDictLoad() {
      return new Promise(resolve => {
        const check = () => {
          if (this.isDictReady) {
            resolve();
          } else {
            setTimeout(check, 100);
          }
        };
        check();
      });
    },

    // 映射报名来源
    mapRegistrationMethod(type) {
      return this.registrationMethodMap[type] || type;
    },

    // 映射培训类型
    mapTrainingType(type) {
      return this.trainingTypeMap[type] || type;
    },

    // 映射缴费状态
    mapPaymentStatus(type) {
      return this.paymentStatusMap[type] || type;
    },

    // 映射开班类型
    mapStartupType(type) {
      return this.startupTypeMap[type] || type;
    },

    // 映射档案状态
    mapRecordStatus(status) {
      return this.recordStatusMap[status] || status;
    },

    // 映射提交状态
    mapSubmitStatus(status) {
      return this.submitStatusMap[status] || status;
    },

    // 查看学员详情
    async handleViewDetail() {
      if (this.selectionDto.length !== 1) {
        this.$message.warning('请选择一个学员');
        return;
      }

      const student = this.selectionDto[0];
      this.form = {
        id: student.id,
        name: student.name,
        phone: student.phonenumber,
        idCard: student.idCard,
        gender: student.sex,
        company: student.company,
        registerSource: student.source,
        trainingType: student.trainType,
        feeStatus: student.feeStatus,
        fileStatus: student.fileStatus,
        fileMissing: student.fileLoss,
        submitStatus: student.submitStatus,
        isCompleted: student.isDone,
        registerTime: student.applyTime,
        remark: student.remark || ''
      };
      this.detailVisible = true;
    },
    handleReset() {
      this.searchForm = {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      };
    },
    handleTabChange(activeTab) {
      this.handleReset();
    },

    // 班级备注相关方法
    handleClassRemark() {
      this.resetClassRemarkForm();
      this.loadClassRemarkHistory();
      this.classDialogVisible = true;
    },

    async loadClassRemarkHistory() {
      this.classRemarkLoading = true;
      try {
        const res = await listRemarksByParams({
          foreignId: this.classId,
          remarkType: "3"
        });
        this.classRemarkHistory = res.rows || [];
      } catch (err) {
        this.$message.error('获取班级备注历史失败：' + (err.msg || err.message));
        this.classRemarkHistory = [];
      } finally {
        this.classRemarkLoading = false;
      }
    },

    async submitClassRemark() {
      this.$refs.classRemarkFormRef.validate(async (valid) => {
        if (valid) {
          this.classRemarkSubmitting = true;
          try {
            await addRemarks({
              foreignId: this.classId,
              remarks: this.classRemarkForm.content,
              remarkType: "3"
            });
            this.$message.success('班级备注提交成功');
            this.classDialogVisible = false;
            this.getList();
          } catch (err) {
            this.$message.error('班级备注提交失败：' + (err.msg || err.message));
          } finally {
            this.classRemarkSubmitting = false;
          }
        }
      });
    },

    resetClassRemarkForm() {
      this.classRemarkForm = { content: "" };
      this.classRemarkHistory = [];
      if (this.$refs.classRemarkFormRef) {
        this.$refs.classRemarkFormRef.resetFields();
      }
    },

    // 学员备注相关方法
    async handleStudentRemark() {
      if (this.selectionDto.length !== 1) {
        this.$message.warning('请选择一个学员');
        return;
      }

      const student = this.selectionDto[0];
      this.resetStudentRemarkForm();
      this.studentRemarkForm = {
        remarks: "",
        studentId: student.id
      };
      this.studentRemarkTitle = `学员 ${student.name} 的备注`;
      this.loadStudentRemarkHistory(student.id);
      this.studentDialogVisible = true;
    },

    async loadStudentRemarkHistory(studentId) {
      this.studentRemarkLoading = true;
      try {
        const res = await listRemarksByParams({
          foreignId: studentId,
          remarkType: "4"
        });
        this.studentRemarkHistory = res.rows || [];
      } catch (err) {
        this.$message.error('获取学员备注历史失败：' + (err.msg || err.message));
        this.studentRemarkHistory = [];
      } finally {
        this.studentRemarkLoading = false;
      }
    },

    async submitStudentRemark() {
      this.$refs.studentRemarkFormRef.validate(async (valid) => {
        if (valid) {
          this.studentRemarkSubmitting = true;
          try {
            await addRemarks({
              foreignId: this.studentRemarkForm.studentId,
              remarks: this.studentRemarkForm.remarks,
              remarkType: "4"
            });
            this.$message.success('学员备注提交成功');
            this.studentDialogVisible = false;
            this.getList();
          } catch (err) {
            this.$message.error('学员备注提交失败：' + (err.msg || err.message));
          } finally {
            this.studentRemarkSubmitting = false;
          }
        }
      });
    },

    resetStudentRemarkForm() {
      this.studentRemarkForm = { remarks: "", studentId: null };
      this.studentRemarkHistory = [];
      if (this.$refs.studentRemarkFormRef) {
        this.$refs.studentRemarkFormRef.resetFields();
      }
    },

    // 学员通知
    handleStudentNotice() {
      this.initNoticeForm();
      this.noticeDialogVisible = true;
    },

    // 初始化通知表单
    initNoticeForm() {
      this.noticeForm = {
        title: '',
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      };
      this.userOptions = [];
      this.loadStudentsData();
    },

    // 加载学员数据
    async loadStudentsData() {
      try {
        const res = await getClassStudents({
          trainingClassId: this.classId,
          pageNum: 1,
          pageSize: 1000 // 加载全部学员用于筛选
        });
        this.allUsers = res.rows.map(item => ({
          studentId: item.registrationDto?.registrationId,
          studentName: item.registrationDto?.studentName,
          idCard: item.registrationDto?.idNumber,
          phone: item.registrationDto?.phonenumber
        }));
      } catch (err) {
        this.$message.error('加载学员数据失败：' + (err.msg || err.message));
      }
    },

    // 发送范围变更
    handleRangeChange(newRange) {
      if (newRange === 'all') {
        this.noticeForm.selectedUsers = [];
      }
    },

    // 清除选择
    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },

    // 查询用户
    queryUsers(query) {
      if (!query) {
        this.userOptions = [];
        return;
      }

      this.userLoading = true;
      setTimeout(() => {
        this.userOptions = this.allUsers.filter(user =>
          user.studentName?.toLowerCase().includes(query.toLowerCase()) ||
          user.idCard?.includes(query) ||
          user.phone?.includes(query)
        );
        this.userLoading = false;
      }, 300);
    },
    handleClassExam(){
      this.$router.push({
        name: '班级考试',
        params: {
          className: this.classUseData.trainingClassName,
          classId: this.classUseData.trainingClassId,
          handoverStatus: this.statusStr(this.classUseData.handoverStatus),
          trainingClassCode: this.classUseData.trainingClassCode,
        }
      });
    },

    // 提交通知
    async submitNotice() {
      this.$refs.noticeForm.validate(async (valid) => {
        if (valid) {
          this.noticeLoading = true;
          try {
            const params = {
              trainingClassId: this.classId,
              content: this.noticeForm.content,
              sendType: this.noticeForm.sendTypes.join(','),
              studentIds: this.noticeForm.range === 'all' ? '' : this.noticeForm.selectedUsers.join(',')
            };

            await studentNoticeProcess(params);
            this.$message.success('通知发送成功');
            this.noticeDialogVisible = false;
          } catch (err) {
            this.$message.error('通知发送失败：' + (err.msg || err.message));
          } finally {
            this.noticeLoading = false;
          }
        }
      });
    },

    // 关闭通知弹窗
    handleNoticeDialogClose() {
      this.noticeDialogVisible = false;
    },
    // 处理子组件传递的编辑事件
    handleEdit(row) {

    },
    // 处理子组件传递的查看预约事件
    handleViewReservations(row) {

    },
    // 处理子组件传递的选择变化事件
    handleSelectionChange(selection) {

    },

    // 获取学员列表
    async getStudentList() {
      try {
        const res = await getClassStudents({
          trainingClassId: this.classId,
          name: this.searchForm.name,
          phone: this.searchForm.phone,
          idCard: this.searchForm.idCard,
          pageNum: this.pageInfo.currentPage,
          pageSize: this.pageInfo.pageSize
        });

        this.studentData = res.rows.map(item => {
          const dto = item.student || {};
          return {
            id: dto.registrationId || "-",
            name: dto.studentName || "-",
            idCard: dto.idNumber || "-",
            sex: dto.sex,
            phonenumber: dto.phonenumber || "-",
            unitName: dto.unitName || "-",
            qualification:dto.qualification,
            position:dto.position
          };
        });
        this.pageInfo.total = res.total || 0;
      } catch (err) {
        this.$message.error('获取学员列表失败：' + (err.msg || err.message));
      }
    },

    // 分页大小变更
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.pageInfo.currentPage = 1;
      this.getStudentList();
    },

    // 当前页变更
    handleCurrentChange(val) {
      this.pageInfo.currentPage = val;
      this.getStudentList();
    },

    // 搜索
    handleSearch() {
      this.pageInfo.currentPage = 1;
      this.getStudentList();
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        name: "",
        phone: "",
        idCard: "",
        reportStatus: ""
      };
      this.pageInfo.currentPage = 1;
      this.getStudentList();
    },

    // 切换搜索显示
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },

    // 刷新
    handleRefresh() {
      this.getList();
      this.getMembersList();
      this.loadDepartments();
      this.loadProjects();
      this.loadTeachers();
    },

    // 班级交接
    handleClassHandover() {
      this.handoverForm = {
        receiveUserId: '',
        remark: ''
      };
      this.handoverDialogVisible = true;
    },

    // 提交班级交接
    async submitHandover() {
      this.$refs.handoverFormRef.validate(async (valid) => {
        if (valid) {
          try {
            await classHandover({
              trainingClassId: this.classId,
              receiveUserId: this.handoverForm.receiveUserId,
              remark: this.handoverForm.remark,
              completeHandover: "false"
            });
            this.$message.success('班级交接申请已提交');
            this.handoverDialogVisible = false;
            this.getList();
          } catch (err) {
            this.$message.error('班级交接失败：' + (err.msg || err.message));
          }
        }
      });
    },

    // 交接标记
    flagHandover() {
      return this.handoverStatus === "1";
    },

    // 培训预约情况
    handleTrainingReservation() {
      this.$router.push({
        name: '实践预约情况',
        params: {
          className: this.classUseData.trainingClassName,
          classId: this.classUseData.trainingClassId,
          handoverStatus: this.statusStr(this.classUseData.handoverStatus),
          trainingClassCode: this.classUseData.trainingClassCode,
        }
      });
    },

    // 签到
    handleSignIn() {
      this.$router.push({
        name: '签到',
        params: {
          className: this.classUseData.trainingClassName,
          classId: this.classUseData.trainingClassId,
          trainingClassCode: this.classUseData.trainingClassCode,
          handoverStatus: this.statusStr(this.classUseData.handoverStatus),
        }
      });
    },

    // 签到情况
    handleSignInStatus() {
      this.$router.push({
        name: '签到统计',
        params: {
          className: this.classUseData.trainingClassName,
          classId: this.classUseData.trainingClassId,
          classStatus: this.statusStr(this.classUseData.handoverStatus),
        }
      });
    },

    // 班级详情导出
    async handleExportClassDetail() {
      try {
        const res = await exportClassDetail(this.classId);
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${this.className}详情.xlsx`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        this.$message.success('班级详情导出成功');
      } catch (err) {
        this.$message.error('导出失败：' + (err.msg || '文件生成失败'));
      }
    },

    // 删除班级
    async handleDeleteClass() {
      this.$confirm(`确定要删除班级"${this.className}"吗？删除后数据不可恢复`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteTrainingClass(this.classId);
          this.$message.success('班级删除成功');
          this.$router.push('/training/classList');
        } catch (err) {
          this.$message.error('删除失败：' + (err.msg || '操作失败'));
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 班级结算
    handleClassSettlement() {
      this.settlementDialogVisible = true;
    },

    // 费用结算导出
    async handleExportFeeSettlement() {
      try {
        const res = await exportFeeSettlement(this.classId);
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${this.className}费用结算.xlsx`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        this.$message.success('费用结算导出成功');
      } catch (err) {
        this.$message.error('导出失败：' + (err.msg || '文件生成失败'));
      }
    }
  }
};
</script>

<style scoped>
.class-detail-page {
  padding: 16px;
  background-color: #fff;
  min-height: calc(100vh - 100px);
}

.top-info {
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
  font-size: 14px;
}

.info-item {
  margin-right: 16px;
  color: #333;
}

.info-splitter {
  color: #ccc;
  margin: 0 8px;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: #fff;
}

.status-pending {
  background-color: #faad14;
}

.status-processing {
  background-color: #1890ff;
}

.status-completed {
  background-color: #52c41a;
}

.search-area {
  margin-bottom: 16px;
}

.search-form {
  padding: 12px 0;
}

.search-input {
  width: 200px;
}

.button-groups {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.button-groups .el-button { padding: 6px 10px; }

.custom-tabs {
  margin-top: 16px;
}

.tab-content {
  padding: 16px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-top: none;
  border-radius: 0 0 4px 4px;
}

.section-container {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  color: #1890ff;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8e8e8;
}

.action-link {
  color: #1890ff;
  cursor: pointer;
}

.operation-btn {
  color: #1890ff;
  padding: 0;
}

.total-amount {
  font-weight: bold;
  color: #f5222d;
}

.qrcode-container {
  text-align: center;
  padding: 20px;
}

.qrcode-img {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  display: block;
}

.qrcode-error {
  color: #f5222d;
  margin-top: 16px;
}

.qrcode-desc {
  margin-top: 16px;
  color: #666;
  font-size: 14px;
}

.settlement-section {
  margin-bottom: 16px;
}

.section-header {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.settlement-select {
  width: 100%;
}

/* 学员详情弹窗样式 */
.detail-form {
  margin-top: 10px;
}
.non-interactive-input {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

/* 学员备注弹窗样式 */
::v-deep .dialog-remark .el-textarea {
  width: 100%;
}
::v-deep .dialog-remark .el-table {
  margin-top: 10px;
}

/* 学员通知弹窗样式 */
.selected-users-form-item {
  margin-top: 10px;
}
.selected-count {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

/* 编辑班级弹窗样式 */
.edit-form {
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-input, .search-select {
    width: 150px;
  }
}

@media (max-width: 768px) {
  .top-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .search-input, .search-select {
    width: 100%;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table .cell {
    padding: 4px 8px !important;
  }
}
</style>
